import axios from "axios";

import {
	handleChangeRequestHeader,
	handleConfigureAuth,
	handleAuthError,
	handleGeneralError,
	handleNetworkError,
} from "./tools";

const baseURL = import.meta.env.VITE_BASE_URL
const axiosInstance = axios.create({ baseURL });

// 请求拦截
axiosInstance.interceptors.request.use((config) => {
	config = handleChangeRequestHeader(config);
	config = handleConfigureAuth(config);
	return config;
});

// 相应拦截
axiosInstance.interceptors.response.use(
	(response) => {
		if (response.status !== 200) return Promise.reject(response.data);
		handleAuthError(response.data.errno);
		handleGeneralError(response.data.errno, response.data.errmsg);
		return response;
	},
	(err) => {
		handleNetworkError(err.response.status);
		return Promise.reject(err.response);
	}
);

// Get请求封装
export const Get = (url, params = {}, clearFn) =>
	new Promise((resolve) => {
		axiosInstance
			.get(url, { params })
			.then((result) => {
				let res;
				if (clearFn !== undefined) {
					res = clearFn(result.data);
				} else {
					res = result.data;
				}
				resolve([null, res]);
			})
			.catch((err) => {
				resolve([err, undefined]);
			});
	});

// Post请求封装
export const Post = (url, data, params = {}) => {
	return new Promise((resolve) => {
		axiosInstance
			.post(url, data, { params })
			.then((result) => {
				resolve([null, result.data]);
			})
			.catch((err) => {
				resolve([err, undefined]);
			});
	});
};